import { _decorator, Collider2D, Component, Contact2DType, find, instantiate, IPhysics2DContact, Node, Prefab, Vec3 } from 'cc';
import { Zombie } from './Zombie';
const { ccclass, property } = _decorator;

@ccclass('PeaBullet')
export class PeaBullet extends Component {

    private speed: number = 300;
    private atk: number = 20;
    @property({ type: Prefab })
    public peaBulletHitPrefab:Prefab;
    public setSpeed(speed: number) {
        this.speed = speed;
    }
    public setAtk(atk: number) {
        this.atk = atk;
    }

    start() {
        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
        this.schedule(()=>{
            this.node.destroy();
        },5);
    }
    onBeginContact(self: Collider2D, other: Collider2D, contact: IPhysics2DContact | null) {
        if (other.group == 1 << 2) {
            setTimeout(() => {
                this.node.destroy();
            }, 1);
            other.node.getComponent(Zombie).takeDamage(this.atk);
            let peaBulletHit=instantiate(this.peaBulletHitPrefab);
            peaBulletHit.setParent(find("Canvas/ForeGround/PeaBulletHitGroup"));
            peaBulletHit.setPosition(this.node.position);
            setTimeout(() => {
                peaBulletHit.destroy();
            }, 1000);
        }
    }
    update(deltaTime: number) {
        this.node.setPosition(this.node.position.add(Vec3.RIGHT.clone().multiplyScalar(this.speed * deltaTime)));
    }
}

